
#include <stdio.h>
#include <string.h>
#include "bindiff.h"
#include <windows.h>
int main(int argc, char *argv[]) {
	char *name = strrchr(argv[0], '/');
	if(!name) name = strrchr(argv[0], '\\');
	if(!name) name = argv[0];
	else name++;
	LoadLibrary("exchndl.dll");
	
	if(argc != 5) {
		fprintf(stderr, "Usage: %s (diff|patch) file.org file.mod file.out\n", name);
		return -1;
	}
	
	FILE * fp;
	if(!(fp = fopen(argv[2], "rb"))) {
		fprintf(stderr, "%s: can't open '%s'\n", name, argv[2]);
		return -1;
	}
	stream_t sin_org = STREAM_INFILE_INIT(fp);
	
	if(!(fp = fopen(argv[3], "rb"))) {
		fprintf(stderr, "%s: can't open '%s'\n", name, argv[3]);
		return -1;
	}
	stream_t sin_mod = STREAM_INFILE_INIT(fp);
	
	if(!(fp = fopen(argv[4], "wb"))) {
		fprintf(stderr, "%s: can't create/overwrite '%s'\n", name, argv[4]);
		return -1;
	}
	stream_t sout = STREAM_OUTFILE_INIT(fp);
	
	bindiff_t bindiff = BIN_DIFF_INIT(&sin_org, &sin_mod);
	if(argv[1][0] == 'p') bindiff.isPatch = 1;
	else if(argv[1][0] != 'd') {
		fprintf(stderr, "%s: expected (diff|patch), got '%s'\n", name, argv[1]);
		return -1;
	}
	stream_t diffstream = BIN_DIFFSTREAM_INIT(&bindiff);

	char buffer[65536]; //TODO: making it 65537 makes a bug!!
	int retcode = StreamPipeline(&diffstream, &sout, buffer, 65535); //TODO: making it 65536 makes a bug!!
	if(retcode != STREAM_EOF) fprintf(stderr, "%s: %i bytes out\n", name, retcode);
	else fprintf(stderr, "%s: processing error!\n", name);
	StreamClose(&diffstream);
	return 0;
}